$(window).load(function(){
	/* 获取微信签名认证，调用接口权限 */
	var getSignatureUrl = window.location.href.split('#')[0];
	var getSignature = wxAddress + "/weixin/sign/getSignature?url="+getSignatureUrl;
	ajaxEncapsulation(getSignature, getSignatureSuc, "", "GET", "true");

	function getSignatureSuc(data){
		if(data.code == "0000"){
			var config = data.data;
			if(config != undefined && config != null){
				wx.config({
					debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId : config.appID, // 必填，appID公众号的唯一标识
					timestamp : config.timestamp, // 必填，生成签名的时间戳
					nonceStr : config.nonceStr, // 必填，生成签名的随机串
					signature : config.signature,// 必填，签名，见附录1
					jsApiList : [ 'getLocation' ]
				});

				wx.ready(function() {
					wx.getLocation({
						type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: function (res) {
							var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
							var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
							var location = latitude+","+longitude;
							var getTxCity = "http://apis.map.qq.com/ws/geocoder/v1/?location="+location+"&key=53IBZ-ZTCAD-DDC4B-P3OJI-SLCW7-VPB5C&coord_type=1&output=jsonp";
							$.ajax({
								type: "GET",
								async: true,
								url: getTxCity,
								dataType: "jsonp",
								jsonp: "callback",
								jsonpCallback:"success_jsonpCallback",
								success: function(data) {
									console.log(data);
									var getTxCityCode =  data.result.ad_info.city_code.substring(3,data.result.ad_info.city_code.length);
									console.log(getTxCityCode);
									var ownerAreaMsg = $('<p class="area-owntitle">您所在的地区</p><div><p class="area-ownposition"><img src="images/coverage_seat.png" /><span citycode="'+getTxCityCode+'">'+data.result.ad_info.city+'</span></p></div>');
									ownerAreaMsg.prependTo(".area-shortcut");
								},
							})
							
						},
						cancel: function (res) {  
							alert('用户拒绝授权获取地理位置');  
						}
					});
				})
			}
		}else{
			warnText($(".red-bg"),"获取微信签名失败！",1000);
		}
	}



	/* 获取公司能够购买的保险险种信息，渲染DOM结构 */
	// 获取公司保险险种信息
	var getInsuranceType = wxAddress + "/insurance/insurancetypes";
	var amountArrObj = new Object();
	ajaxEncapsulation(getInsuranceType, getInsuranceTypeSuc, "", "GET", "false");

	function getInsuranceTypeSuc(data){
		console.log(data);
		if(data.code == "0000"){
			var insuranceType = data.data;
			if(insuranceType != null && insuranceType != "" && insuranceType != undefined){
				$(".auto-startdata").show();
				for(var i=0;i<insuranceType.length;i++){// 遍历所有保险，除开单独的不计免赔险和交强险
					if(insuranceType.length <=1 && insuranceType[i].code == "FORCEPREMIUM"){
						$(".biz-content").hide();
					}
					if(insuranceType[i].type_name.indexOf("不计免赔") == -1 && insuranceType[i].code != "FORCEPREMIUM"){
						var noSdew = $('<div class="coverage-content isflexbox"><p class="coverage-title isflex">'+insuranceType[i].type_name+'</p><div class="coverage-right isflex bizchoice" id="code-'+insuranceType[i].code+'"><p class="coverage-text">不投保</p><img class="coverage-arrow" src="images/right_arrow.png" /></div></div>');
						noSdew.appendTo(".biz-main");
						var amountArr = new Array();
						if(insuranceType[i].amount_range != "Y"){
							amountArr = insuranceType[i].amount_range.split(",");
							amountArr.unshift("不投保");
						}else{
							amountArr[0] = "不投保";
							amountArr[1] = "投保";
						}
						var amountArrKey = "code-"+insuranceType[i].code;
							amountArrObj[amountArrKey] = amountArr;
					}
					// 找出交强险
					if(insuranceType[i].code == "FORCEPREMIUM"){
						$(".sali-content").show();
					}
				}
				for(var j=0;j<insuranceType.length;j++){// 遍历所有保险，除开交强险，将不计免赔险加入到上面遍历的保险中
					if(insuranceType[j].type_name.indexOf("不计免赔") != -1 && insuranceType[j].code != "FORCEPREMIUM"){
						var haveSdew = $('<div class="sdew-div isflexbox"><span class="coverage-sdew">不计免赔</span><img class="sdew-img" src="images/coverage_un.png" /><input class="sdew-choice code-'+insuranceType[j].code+'" type="radio" /></div>');
						var appendTarget = insuranceType[j].code.substring(1,insuranceType[j].code.length);
						appendTarget = "#code-"+appendTarget;
						haveSdew.insertBefore(appendTarget);
					}
				}
				console.log(amountArrObj);
			}
		}else{
			warnText($(".red-bg"),"获取险种信息失败！",1000);
		}
	}



	/* 自动匹配保险起期 */
	$(".coverage-main .auto-startdata").delegate("p", "click", function(event){
		if(defaultInsurance.biBeginDate != null && defaultInsurance.biBeginDate != "" && defaultInsurance.biBeginDate != undefined){
			$(".biz-text").val(defaultInsurance.biBeginDate);
		}
		if(defaultInsurance.ciBeginDate != null && defaultInsurance.ciBeginDate != "" && defaultInsurance.ciBeginDate != undefined){
			$(".sali-text").val(defaultInsurance.ciBeginDate);
		}
	});



	/* 获取车主默认保险险种信息，渲染DOM结构 */
	var defaultInsurance = JSON.parse(localStorage.getItem("eBizDefaultInsurance"));
	if(defaultInsurance){
		if(defaultInsurance.biBeginDate != null && defaultInsurance.biBeginDate != "" && defaultInsurance.biBeginDate != undefined){
			$(".biz-text").val(defaultInsurance.biBeginDate);
		}
		if(defaultInsurance.ciBeginDate != null && defaultInsurance.ciBeginDate != "" && defaultInsurance.ciBeginDate != undefined){
			$(".sali-text").val(defaultInsurance.ciBeginDate);
		}
		for(var i in defaultInsurance.coverageList){
			var insuranceId = "#code-" + defaultInsurance.coverageList[i].coverageCode;
			var insuranceClass = ".code-" + defaultInsurance.coverageList[i].coverageCode;
			if(defaultInsurance.coverageList[i].insuredAmount == "Y"){
				$(insuranceId).find(".coverage-text").text("投保");
				$(insuranceId).siblings(".sdew-div").show();
				$(insuranceClass).prop("checked",true);
				$(insuranceClass).siblings("img").attr("src", "images/coverage_on.png");
				$(insuranceClass).parent(".sdew-div").show();
			}
			if(defaultInsurance.coverageList[i].insuredAmount != "Y" && defaultInsurance.coverageList[i].insuredAmount != "" && defaultInsurance.coverageList[i].insuredAmount != null && defaultInsurance.coverageList[i].insuredAmount != undefined){
				$(insuranceId).find(".coverage-text").text(defaultInsurance.coverageList[i].insuredAmount);
				$(insuranceId).siblings(".sdew-div").show();
				$(insuranceClass).prop("checked",true);
				$(insuranceClass).siblings("img").attr("src", "images/coverage_on.png");
				$(insuranceClass).parent(".sdew-div").show();
			}
		}
	}



	/* 交强险及商业险的处理：选择日期，开启关闭（是否购买） */
	// 交强险-日期选择插件
	new DateSelector({
		input: "sali-data",
		container: "saliDataContainer",
		type: 0,
		param: [1,1,1,0,0],
		beginTime: [],
		endTime: [],
		recentTime: [],
		success: function(arr){
			for(var i=0;i<arr.length;i++){
				if(arr[1]<10){var monthData = "0"+ arr[1];}
				else{var monthData = arr[1];}
				if(arr[2]<10){var dayData = "0"+ arr[2];}
				else {var dayData = arr[2];}
			}
			$(".sali-text").val(arr[0]+"-"+monthData+"-"+dayData);
		}
	});

	$("#saliDataContainer").delegate("#date-selector-bg-saliDataContainer", "touchmove", function(e){
		e.preventDefault();
	});

	// 商业险-日期选择插件
	new DateSelector({
		input: "biz-data",
		container: "bizDataContainer",
		type: 0,
		param: [1,1,1,0,0],
		beginTime: [],
		endTime: [],
		recentTime: [],
		success: function(arr){
			for(var i=0;i<arr.length;i++){
				if(arr[1]<10){var monthData = "0"+ arr[1];}
				else{var monthData = arr[1];}
				if(arr[2]<10){var dayData = "0"+ arr[2];}
				else {var dayData = arr[2];}
			}
			$(".biz-text").val(arr[0]+"-"+monthData+"-"+dayData);
		}
	});

	$("#bizDataContainer").delegate("#date-selector-bg-bizDataContainer", "touchmove", function(e){
		e.preventDefault();
	});

	var issali = 1;
	var isbiz = 1;
	// 交强险关闭按钮
	$(".issali").on("click", function(){
		if(issali == 1){
			$(this).find("p").stop().animate({left: "0"},"normal",function(){
				$(this).parent().css({backgroundColor: "#F0F0F0"});
				$(".sali-main").hide();
				issali = 0;
			});
		}else if(issali == 0){
			$(this).find("p").stop().animate({left: "46.2025%"},"normal",function(){
				$(this).parent().css({backgroundColor: "#EA4040"});
				$(".sali-main").show();
				issali = 1;
			});
		}
	})

	// 商业险关闭按钮
	$(".isbiz").on("click", function(){
		if(isbiz == 1){
			$(this).find("p").stop().animate({left: "0"},"normal",function(){
				$(this).parent().css({backgroundColor: "#F0F0F0"});
				$(".biz-main").hide();
				isbiz = 0;
			});
		}else if(isbiz == 0){
			$(this).find("p").stop().animate({left: "46.2025%"},"normal",function(){
				$(this).parent().css({backgroundColor: "#EA4040"});
				$(".biz-main").show();
				isbiz = 1;
			});
		}
	})



	/* 险种处理，相关插件 */
	// 不计免赔按钮：选择是否购买不计免赔
	$(".coverage-content").delegate(".sdew-div", "click", function(){
		if($(this).find("input").prop("checked")){
			$(this).find("input").prop("checked",false);
			$(this).find("img").attr("src", "images/coverage_un.png");
		}else{
			$(this).find("input").prop("checked",true);
			$(this).find("img").attr("src", "images/coverage_on.png");
		}
	})

	// 选择插件：保险选项按钮（不含不计免赔）
	$(".coverage-content").delegate(".coverage-right", "click", function(){
		$("#insuranceList").html("");
		console.log(amountArrObj[$(this).attr("id")]);
		var _this = $(this);
		var mobileSelect = new MobileSelect({
			trigger: "#insuranceList", 
			title: "选择类型",  
			wheels: [
						{data: amountArrObj[$(this).attr("id")]}
					],
			position:[0],
			callback:function(indexArr, data){
				_this.find(".coverage-text").text(data[0]);
				if(data[0] != "不投保"){
					_this.siblings(".sdew-div").show();
				}else if(data[0] == "不投保"){
					_this.siblings(".sdew-div").hide();
				}
			},
			ensureBtnText: "确认",
			cancelBtnText: "取消",
			ensureBtnColor: "#EA4040",
			cancelBtnColor: "#EA4040",
			titleColor: "#333",
			titleBgColor: "#FFF",
			textColor: "#333",
			bgColor: "#FFF"
		});
		mobileSelect.show();
	})
	
	$("body").delegate(".mobileSelect .grayLayer", "touchmove", function(e){
		e.preventDefault();
	});



	/* 搜索功能，选择投保城市,加载城市列表，渲染DOM结构 */
	// 查询城市列表，插入结构
	var getCityAll = wxAddress + "/weixin/getCityAll";
	ajaxEncapsulation(getCityAll, getCityAllSuc, "", "GET", "true");

	function getCityAllSuc(data){
		console.log(data);
		if(data.code == "0000"){
			for(var i=0;i<26;i++){
				var letterCode = String.fromCharCode(65+i);
				var cityAllLi = $('<li><div class="select-pinyin'+letterCode+'">'+letterCode+'</div></li>');
				cityAllLi.appendTo($(".city-list ul"));
			}
			var cityAllList = data.data;
			for(var i=0;i<cityAllList.length;i++){
				var cityAllLiP = $('<p citycode="'+cityAllList[i].gbcode+'">'+cityAllList[i].cityName+'</p>');
				var targetCityAllLi = ".select-pinyin" + cityAllList[i].pinyincode;
				cityAllLiP.insertAfter($(targetCityAllLi));
			}
		}else{
			warnText($(".red-bg"),"获取城市列表失败！",1000);
		}
	}

	// 查询框聚焦情况
	$(".input-select").on("focus", function(){
		$(this).addClass("isflex");
		$(this).css({"marginRight": "0.90666666rem"});
	})

	// 查询框失焦情况
	$(".input-select").on("blur", function(){
		if($(this).val()==""){
			$(".img-close").hide();
			$(this).removeClass("isflex");
			$(this).css({"marginRight": "0"});
			$(".select-result ul").html("");
			$(".select-result").hide();
			$(".area-whole").show();
		}
	})

	// 查询框输入监听
	$(".input-select").on("input propertychange", function(){
		if($(this).val()==""){
			$(".img-close").hide();
			$(this).css({"marginRight": "0.90666666rem"});
			$(".select-result ul").html("");
			$(".select-result").hide();
			$(".area-whole").show();
		}else{
			$(".img-close").show();
			$(this).css({"marginRight": "0"});
		}
	})

	// 查询框清空按钮
	$(".img-close").on("click", function(){
		$(".input-select").val("").focus();
		selectOldValue = "";
		$(".input-select").css({"marginRight": "0.90666666rem"});
	})

	// 搜索功能
	var selectOldValue = $(".input-select").val();
	var selectNewValue = "";
	var selectTimer;
	var getCity = wxAddress + "/weixin/getCity";
	$(".input-select").on("keydown", function(){
		clearTimeout(selectTimer);
	})

	$(".input-select").on("keyup", function(){
		selectNewValue = $(".input-select").val();
		selectTimer = setTimeout(function(){
			if(selectNewValue != selectOldValue && selectNewValue != ""){
				var selectData = {
					cityName: selectNewValue
				}
				$(".select-result").show();
				$(".area-whole").hide();
				$(".select-result ul").html("");
				ajaxEncapsulation(getCity, getCitySuc, "", "POST", "true", selectData);
				selectOldValue = selectNewValue;
			}else if(selectNewValue == ""){
				$(".select-result ul").html("");
				$(".select-result").hide();
				$(".area-whole").show();
			}
		}, 2000);
	})

	function getCitySuc(data){
		console.log(data);
		if(data.code == "0000"){
			if(data.data.length == 0){
				warnText($(".red-bg"),"未查询到相关城市！",1000);
			}else{
				var cityList = data.data;
				for(var i=0;i<cityList.length;i++){
					var cityListName = $('<li citycode="'+cityList[i].gbcode+'">'+cityList[i].cityName+'</li>');
					cityListName.appendTo($(".select-result ul"));
				}
			}
		}else{
			warnText($(".red-bg"),"连接错误，获取失败！",1000);
		}	
	}

	// 点击填写所选择的城市
	$(".select-result ul").delegate("li", "click", function(){
		choiceCity($(this));
	})

	$(".area-shortcut").delegate(".area-ownposition", "click", function(){
		choiceCity($(this).find("span"));
	})

	$(".area-hotlist ul li").delegate("p", "click", function(){
		choiceCity($(this));
	})

	$(".city-list ul li").delegate("p", "click", function(){
		choiceCity($(this));
	})
	
	function choiceCity(target){
		$(".city-text").val(target.text());
		$(".city-text").attr("citycode", target.attr("citycode"));
		$(".area-main").hide();
		$(".coverage-main").show();
		$("title").text("险种信息");
	}

	// 拼音索引
	$(".select-pinyin li").on("click", function(){
		var targetTop = $(".select-pinyin"+$(this).text()).offset().top;
		$(".city-pinyin").text($(this).text());
		$(".city-pinyin").fadeIn();
		timer = setTimeout(function(){
			clearInterval(timer);
			$(".city-pinyin").fadeOut();
		},500)
		$("html,body").stop().animate({scrollTop: targetTop},"normal");
	})

	//选择城市按钮
	$(".choice-city").on("click", function(){
		$(".coverage-main").hide();
		$(".area-main").show();
		$("title").text("城市");
		var htmlHeight = $(window).height();
		var selectPinYinHeight = $(".select-pinyin").height();
		var selectPinYinTop = (htmlHeight-selectPinYinHeight) / 2;
		$(".select-pinyin").css("top", selectPinYinTop);
	})

	// 提交报价按钮
	var postSaveCoverage = wxAddress + "/weixin/saveCoverageNew";
	var eBizCarInfoNew = JSON.parse(localStorage.getItem("eBizCarInfoNew"));
	var eBizCarLicenseNo = eBizCarInfoNew.licenseNo;// 获取车牌号
	var postArr = new Array();
	var biBeginDatas,ciBeginDates;
	$(".coverage-next p").on("click", function(){
		if($(".city-text").val() == ""){
			warnText($(".red-bg"),"请选择投保城市！",1000);
				return false;
		}else{
			citycode = $(".city-text").attr("citycode");
		}
		postArr = [];
		if(issali == 1){ // 交强险
			var postArrObj = new Object();
			postArrObj.coverageCode = "FORCEPREMIUM";
			postArrObj.insuredAmount = "Y";
			postArrObj.flag = "";
			postArr.push(postArrObj);
			if($(".sali-text").val() == ""){
				warnText($(".red-bg"),"请选择交强险注册日期！",1000);
				return false;
			}else{
				ciBeginDates = $(".sali-text").val();
			}

		}else{
			ciBeginDates = "";
		}
		if(isbiz == 1){// 商业险
			if($(".biz-text").val() == ""){
				warnText($(".red-bg"),"请选择商业险保险起期！",1000);
				return false;
			}else{
				biBeginDates = $(".biz-text").val();
			}
			for(var i=0;i<$(".coverage-content input:radio").length;i++){
				if($($(".coverage-content input:radio")[i]).parent(".sdew-div").siblings(".coverage-right").find(".coverage-text").text() != "不投保"){
					if($($(".coverage-content input:radio")[i]).prop("checked")) {
						var postArrObj = new Object();
						postArrObj.coverageCode = $($(".coverage-content input:radio")[i]).attr("class").split("code-")[1];
						postArrObj.insuredAmount = "Y";
						if(postArrObj.coverageCode == "F"){
							postArrObj.flag = 1;
						}else{
							postArrObj.flag = "";
						}
						postArr.push(postArrObj);
					}
				}
			}
			for(var j=0;j<$(".coverage-right").length;j++){
				if($($(".coverage-right")[j]).find(".coverage-text").text() == "投保"){
					var postArrObj = new Object();
					postArrObj.coverageCode = $($(".coverage-right")[j]).attr("id").split("-")[1];
					postArrObj.insuredAmount = "Y";
					if(postArrObj.coverageCode == "F"){
						postArrObj.flag = 1;
					}else{
						postArrObj.flag = "";
					}
					postArr.push(postArrObj);
				}else if($($(".coverage-right")[j]).find(".coverage-text").text() != "投保" && $($(".coverage-right")[j]).find(".coverage-text").text() != "不投保"){
					var postArrObj = new Object();
					postArrObj.coverageCode = $($(".coverage-right")[j]).attr("id").split("-")[1];
					postArrObj.insuredAmount = $($(".coverage-right")[j]).find(".coverage-text").text();
					if(postArrObj.coverageCode == "F"){
						postArrObj.flag = 1;
					}else{
						postArrObj.flag = "";
					}
					postArr.push(postArrObj);
				}
			}
			console.log(postArr);
		}else{
			biBeginDates = "";
		}
		if(issali == 0 && isbiz == 0){
			warnText($(".red-bg"),"交强险和商业险请至少选择一个！",1000);
			return false;
		}
		if(postArr.length == 0){
			warnText($(".red-bg"),"请至少选购一种保险！",1000);
			return false;
		}
		$(".masklayer").show();
		$(".maskImg").show();
		var postData = {
			biBeginDate: biBeginDates,
			ciBeginDate: ciBeginDates,
			coverageList: postArr,
			licenseNo: eBizCarLicenseNo,
			citycode: citycode
		}
		console.log(postData);
		console.log(JSON.stringify(postData));
		ajaxEncapsulation(postSaveCoverage, postSaveCoverageSuc, postSaveCoverageErr, "POST", "true", JSON.stringify(postData), "", "application/json; charset=utf-8");
	})

	function postSaveCoverageSuc(data){
		console.log(data);
		$(".masklayer").hide();
		$(".maskImg").hide();
		if(data.code == "0000"){
			var insuranceCompanyList = data.data;
			window.localStorage.setItem("eBizCompanyList", JSON.stringify(insuranceCompanyList));
			window.location.href = "bizscheme.html";
		}else {
			warnText($(".red-bg"),"获取保险公司列表失败！",1000);
		}
	}

	function postSaveCoverageErr(data){
		$(".masklayer").hide();
		$(".maskImg").hide();
		warnText($(".red-bg"),"获取保险公司列表失败！",1000);
	}
})